const { Service } = require("egg");

class UserService extends Service {
    /**
     * 添加一个用户
     * @param {object} param0 要保存的用户信息
     */
    async createUser({ mobile, nickname, email, rid, did }) {
        let sql = `insert into user (mobile, nickname, email, rid, did) value (?, ?, ?, ?, ?)`;
        let params = [mobile, nickname, email, rid, did];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 根据用户手机号，获取用户信息
     * @param {string} mobile 用户手机号
     */
    async findByMobile(mobile) {
        let sql = `
            select u.id as uid, u.mobile, u.nickname, r.id as rid, r.name as rname
            from user as u
            join role as r on u.rid = r.id
            where mobile = ?
            limit 0, 1
        `;
        let params = [mobile];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 根据角色id，获取用户列表
     * @param {number} rid 角色id
     */
    async getUserListByRid(rid) {
        let sql = `
            select u.id as uid, u.mobile, u.nickname, u.email, u.status, d.name as dname
            from user as u
            join dept as d on u.did = d.id
            where u.rid = ?;
        `;
        let params = [rid];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 根据部门 id，获取用户列表
     * @param {number} did 部门 id
     */
    async getUserListByDid(did) {
        let sql = "select * from user where did = ?";
        let params = [did];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 根据 id 批量删除用户
     * @param {string}} uids 逗号分隔的 id 列表字符串
     */
    async removeUserList(ids) {
        let sql = "delete from user where id in ?";
        let params = [[ids.split(",")]];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }
}

module.exports = UserService;
